<?php

namespace App\Service\Common;

use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Service\OpenShop\Feishu\UserExtContractService;
use Kuafu\File\PrivateFileUtil;
use Kuafu\Qiyuesuo\request\DocumentDownloadRequest;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class UserContractService
{
    /**
     * @param int $contractId
     * @param OpenShopSignOrderModel $signOrderModel
     * @param array $contractResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function handleCommonGenerateResponse(
        int $contractId,
        OpenShopSignOrderModel $signOrderModel,
        array $contractResponse
    ) {
        $signUrl = $contractResponse["signUrl"];
        OpenShopUserContractModel::query()->where("id", $contractId)->update([
            "categoryId"    => $contractResponse["contractResponse"]["category"]["id"],
            "categoryName"  => $contractResponse["contractResponse"]["category"]["name"],
            "contractExtNo" => $contractResponse["contractResponse"]["id"],
        ]);

        $userExtContractService = new UserExtContractService();
        $fileSystem             = app()->get('files');
        $dir                    = app()->storagePath() . "/" . date("Y-m-d");
        if (!$fileSystem->isDirectory($dir)) {
            $fileSystem->makeDirectory($dir, 0777, true);
        }

        OpenShopUserExtContractModel::query()->insert(
            collect($contractResponse["contractResponse"]["documents"])->map(function ($v) use (
                $signOrderModel,
                $signUrl,
                $dir,
                $fileSystem,
                $userExtContractService,
                $contractId
            ) {
                $documentDownloadRequest = new DocumentDownloadRequest($v['id']);
                $filePath                = $dir . "/" . $v["id"] . ".pdf";
                $userExtContractService::handleResponse(
                    $userExtContractService->getSdkClient()->downloadService($documentDownloadRequest,
                        $filePath),
                    "契约锁合同转oss - 下载文件失败： 【 {$v["id"]} 】"
                );
                $ossInfo = PrivateFileUtil::uploadFile(
                    $filePath,
                    'pdf',
                    generateFileKey() . ".pdf"
                );
                $fileSystem->delete($filePath);

                return [
                    'contractId'    => $contractId,
                    'contractUrl'   => $signUrl,
                    'contractExtNo' => $v['id'],
                    'previewUrl'    => $ossInfo["path"],
                    'contractName'  => vsprintf("%s.%s-%s", ["No", $signOrderModel->shopCode, $v['title']]),
                    'createdAt'     => time(),
                    'updatedAt'     => time()
                ];
            })->values()->toArray()
        );
    }


    /**
     * 续签合同 - 回写
     *
     * @param string $bizId
     * @param array $contractResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public static function handleGenerateRenewContract(
        string $bizId,
        array $contractResponse
    ) {
        list($orderNo, $contractId) = explode("-", $bizId);
        $orderDetail = OpenShopSignOrderModel::getOrderDetailByOrderNo($orderNo);
        self::handleCommonGenerateResponse($contractId, $orderDetail, $contractResponse);
    }
}
